package com.idol.logger.core.printer.window.panel

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.os.Build
import android.view.*
import com.idol.logger.R
import com.idol.logger.core.printer.window.IdolWindowPrinter
import kotlin.math.abs

internal class IdolTogglePanel(
    private val application: Application,
    private val openClick: () -> Unit
) {
    private var isAttached = false

    //region ###-------------- FrameLayout --------------------------------------------------------
    private val layout: View by lazy {
        LayoutInflater.from(application).inflate(R.layout.idol_float_button, null).also {
            it.setOnClickListener {
                if (isAttached) onDetachedFromWindow()
                openClick.invoke()
            }
            it.setOnTouchListener(touchListener)
        }
    }

    private val layoutParams by lazy {
        WindowManager.LayoutParams().also {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                it.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                it.type = WindowManager.LayoutParams.TYPE_PHONE
            }
            it.gravity = Gravity.END or Gravity.TOP
            it.y = IdolWindowPrinter.windowHeight
            it.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            it.width = WindowManager.LayoutParams.WRAP_CONTENT
            it.height = WindowManager.LayoutParams.WRAP_CONTENT
        }
    }

    fun setVisibility(display: Boolean) {
        layout.visibility = if (display) View.VISIBLE else View.GONE
    }
    //endregion

    //region ###-------------- windowManager --------------------------------------------------------
    private val windowManager: WindowManager by lazy {
        application.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    }

    fun onAttachedToWindow() {
        if (!isAttached) {
            isAttached = true
            windowManager.addView(layout, layoutParams)
        }
    }

    fun onDetachedFromWindow() {
        if (isAttached) {
            isAttached = false
            windowManager.removeView(layout)
        }
    }
    //endregion

    //region ###-------------- OnTouchListener --------------------------------------------------------
    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    private var mTouchStartY: Int = 0
    private var mTouchCurrentY: Int = 0

    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    private var mStartY: Int = 0
    private var mStopY: Int = 0

    //判断悬浮窗口是否移动，这里做个标记，防止移动后松手触发了点击事件
    private var isMove: Boolean = false

    @SuppressLint("ClickableViewAccessibility")
    private val touchListener = View.OnTouchListener { _, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                isMove = false
                mTouchStartY = event.rawY.toInt()
                mStartY = event.y.toInt()
            }
            MotionEvent.ACTION_MOVE -> {
                mTouchCurrentY = event.rawY.toInt()
                layoutParams.y += mTouchCurrentY - mTouchStartY
                windowManager.updateViewLayout(layout, layoutParams)
                mTouchStartY = mTouchCurrentY
            }
            MotionEvent.ACTION_UP -> {
                mStopY = event.y.toInt()
                if (abs(mStartY - mStopY) >= 1) isMove = true
            }
        }
        isMove//如果是移动事件不触发OnClick事件，防止移动的时候一放手形成点击事件
    }
    //endregion

}